package level4.iso
{
	import flash.geom.Point;
	/**
	 * 等角坐标,屏幕坐标转换工具类
	 * */
	public class IsoUtil
	{
		//精确的y,1.2247,cos(30)*1.414(根2)
		public static const Y_CORRECT:Number = Math.cos(-Math.PI/6)*Math.SQRT2;
		
		public function IsoUtil()
		{
		}
		/**
		 * 等角坐标转屏幕坐标,公式
		 * sx = x-z
		 * sy =1.2247*y +(x+z)/2
		 * */
		public static function IsoToScreen(point:Point3D):Point{
			var sx:Number = point.x - point.z;
			var sy:Number = Y_CORRECT * point.y +(point.x+point.z)*0.5;
			return new Point(sx,sy);
		}
		/**
		 * 等角坐标 转 网格坐标
		 * 
		 * 注意:tile的注册点在中心点,使用Math.round.
		 * tile的注册点在菱形的上点.使用Math.floor.
		 * */
		public static function IsoToGrid(pt3d:Point3D,size:int):Point{
			var tx:int = Math.round(pt3d.x / size);
			var ty:int = Math.round(pt3d.z / size);
			return new Point(tx,ty);
		}
		/**
		 * 等角 -> 网格 -> 屏幕
		 * 如此,坐标便 实现网格对齐
		 * */
		public static function IsoToGridToScreen(point:Point3D,size:int):Point{
			var gridCoord:Point = IsoToGrid(point,size);
			return GridToScreen(gridCoord,size);
		}
		/**
		 * 屏幕坐标转等角坐标,公式
		 * x = sy + sx/2
		 * y = 0;
		 * z = sy - sx/2
		 * */
		public static function screenToIso(point:Point):Point3D{
			var x:Number = point.y + point.x * 0.5;
			var y:Number = 0;
			var z:Number = point.y - point.x *0.5;
			return new Point3D(x,y,z);
		}
		/**
		 * 根据 屏幕坐标 获取 网格坐标
		 * */
		public static function ScreenToGrid(pt:Point,size:int):Point{
			var pt3d:Point3D = IsoUtil.screenToIso(pt);
			return IsoToGrid(pt3d,size);
		}
		/**
		 * 屏幕->网格->iso
		 * */
		public static function ScreenToGridToIso(pt:Point,size:int):Point3D{
			return GridToIso(ScreenToGrid(pt,size),size);
		}
		
		/**
		 * 网格坐标转 屏幕坐标
		 * */
		public static function GridToScreen(gridCoord:Point,size:int):Point{
			return IsoToScreen(GridToIso(gridCoord,size));
		}
		/***
		 * 网格坐标 转 等角坐标
		 * */
		public static function GridToIso(gridCoord:Point,size:int):Point3D{
			var nx:int = gridCoord.x * size;
			var ny:int = gridCoord.y * size;
			return new Point3D(nx,0,ny);
		}
	}
}